'use strict';

module.exports = app => {
  const { STRING, INTEGER } = app.Sequelize;

  const Client = app.model.define('client', {
    id: {
      type         : INTEGER,
      primaryKey   : true,
      field        : 'id',
      autoIncrement: true,
    },
    lid         : STRING,
    userEmail   : STRING,
    clientId    : { type: STRING, unique: true },
    clientSecret: STRING,
    name        : STRING,
    redirectUri : STRING,
    url         : STRING,
    grants      : STRING,
    publicKey   : STRING,
    privateKey  : STRING,
  }, {
    createdAt: 'createdAt',
    updatedAt: 'updatedAt',
    tableName: 'zconnect-client',
  });

  // 通过clientId 和 clientSecret(可选) 搜索应用信息
  Client.getClient = async function(clientId, clientSecret = null) {
    const params = {
      clientId,
    };
    if (clientSecret) {
      params.clientSecret = clientSecret;
    }
    const client = await this.findOne({
      where: params,
    });
    return client;
  };

  // 通过应用字段搜索应用信息
  Client.queryClient = async function(params) {
    return this.findOne({
      where     : params,
      attributes: {
        exclude: ['clientSecret'],
      },
    });
  };

  // 注册应用信息
  Client.add = async function(fields) {
    return this.create(fields);
  };

  return Client;
};
